import { Model, DataTypes } from 'sequelize';
import sequelize from '@/config/database';
import User from './user.model';
import Role from './role.model';

// 定义用户角色关联属性接口
interface UserRoleAttributes {
  userId: number;
  roleId: number;
}

// 用户角色关联模型类
class UserRole extends Model<UserRoleAttributes> implements UserRoleAttributes {
  public userId!: number;
  public roleId!: number;

  // 时间戳
  public readonly createdAt!: Date;
  public readonly updatedAt!: Date;
}

UserRole.init(
  {
    userId: {
      type: DataTypes.BIGINT,
      primaryKey: true,
      field: 'user_id',
      references: {
        model: User,
        key: 'user_id'
      }
    },
    roleId: {
      type: DataTypes.BIGINT,
      primaryKey: true,
      field: 'role_id',
      references: {
        model: Role,
        key: 'role_id'
      }
    }
  },
  {
    sequelize,
    tableName: 'sys_user_role',
    timestamps: false
  }
);

// 建立关联关系
User.belongsToMany(Role, {
  through: UserRole,
  foreignKey: 'userId',
  otherKey: 'roleId',
  as: 'roles'
});

Role.belongsToMany(User, {
  through: UserRole,
  foreignKey: 'roleId',
  otherKey: 'userId',
  as: 'users'
});

// 为UserRole添加Role关联以便在查询时使用
UserRole.belongsTo(Role, {
  foreignKey: 'roleId',
  as: 'role'
});

// 为UserRole添加User关联
UserRole.belongsTo(User, {
  foreignKey: 'userId',
  as: 'user'
});

export default UserRole;